﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using Npgsql;
using NpgsqlTypes;
namespace Tuto.DAL
{
    /// <summary>
    ///     Author : Tidiane SIDIBE
    ///     Handle the connection to the Database
    ///     Use the Syngleton Pattern
    /// </summary>
    public class DbConnexion
    {
        // The Connexion
        private NpgsqlConnection conn = new NpgsqlConnection();
        private static DbConnexion _instance = null;
        private static Object locker = new Object();
        // Connection Stringg
        private string _connectionString = String.Empty;
        public string connectionString 
        {
            get
            {
                return this._connectionString;
            }
            set
            {
                this._connectionString = value;
            }
        }
        // The connection instance
        public static DbConnexion instance
        {
            get
            {
                lock (locker)
                {
                    if (_instance == null)
                        return new DbConnexion();
                    else
                        return _instance;
                }
            }
        }

        /// <summary>
        ///     Get a created and opened connection object 
        /// </summary>
        /// <returns></returns>
        public NpgsqlConnection getDbConnection()
        {
            conn.ConnectionString = String.Format("server={0};port={1};user={2};password={3};database={4}", "localhost", "5432", "postgres", "Tsid0407@", "tuto_db");
            try
            {
                conn.Open();
                Console.Out.WriteLine("opened ... " + conn.ConnectionString);
            }
            catch (Exception e)
            {
                Console.Out.WriteLine(e.Message);
            }
            return conn;
        }

        /// <summary>
        ///     Loose the Database connection
        /// </summary>
        public void loseDbConnection()
        {
            if (this.conn != null)
            {
                if (this.conn.State != System.Data.ConnectionState.Closed)
                {
                    this.conn.Close();
                }
            }
        }
    }
}